<?php require_once(BASEPATH.'application/controllers/validaciones.php');
//Cliente
class smov extends validaciones {
	
	var $usuario;
	var $super;
	
	function smov(){
		parent::Controller(); 
		$this->load->library("rapyd");
		$this->usuario=$this->session->userdata['usuario'];
		$this->super=$this->datasis->dameval("SELECT usu_tip FROM usuarios WHERE usu_login='$this->usuario'");
	}

	function index(){
		redirect("ventas/smov/filteredgrid");
	}
	function filteredgrid(){
		
		
		$atts = array(
			'width'      => '800',
			'height'     => '600',
			'scrollbars' => 'yes',
			'status'     => 'yes',
			'resizable'  => 'yes',
			'screenx'    => '0',
			'screeny'    => '0'
		);
			
				
		$this->rapyd->load("datafilter","datagrid2");
		$this->rapyd->uri->keep_persistence();
		
		$link2=site_url('inventario/common/get_zona');
		$link3=site_url('inventario/common/get_estados');
				
		$filter = new DataFilter("B&uacute;squeda de Movimientos de Clientes");
		
		$select=array( 'cod_cli',  'nombre',  'tipo_doc',  'numero',  'serie',  'fecha',
		  'monto',  'impuesto',  'abonos',  'letras',  'presup',  'usuario',  'estampa', 
		   'reteiva',  'devuelta',  'vence',  'idfactura',  'transac',  'moneda'); 
		$filter->db->select($select);
		$filter->db->from("smov AS a");
		$filter->db->where("tipo_doc <>","FC");
		
		$ano=date("Y");
        $mes=date("m");
        
        $filter->fechad = new dateonlyField('Desde', 'fechad','d/m/Y');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','d/m/Y');
		$filter->fechah->size=$filter->fechad->size=12;
		$filter->fechah->operator='<=';
        $filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0,01, 1, $ano));
        $filter->fechah->insertValue = date("Y-m-d", mktime(0, 0, 0,$mes+3, 1, $ano));
		$filter->fechad->clause  =$filter->fechah->clause ='where';
		$filter->fechad->db_name =$filter->fechah->db_name='fecha';
		$filter->fechad->operator='>=';
		
		$filter->serief = new inputField('N&deg; Serie', 'serie');
		$filter->serief->size=20;
		$filter->serief->maxlength=3;
		
		$filter->factura = new inputField('Comprobante', 'numero');
		$filter->factura->size=20;
		$filter->factura->maxlength=11;
		
		$filter->nombre= new inputField("Nombre de Cliente"  , "nombre");
		$filter->nombre->size=50;
		
        $filter->banco = new dropdownField("Banco", "serie");
		$filter->banco->style='width:200px;';
        $filter->banco->option("","Todos");
		$filter->banco->options("SELECT codigo, descrip FROM bancos ORDER BY codigo" );
		
		$filter->tipo_doc = new dropdownField("Tipo de Documento", "tipo_doc");
		$filter->tipo_doc->style='width:200px;';
        $filter->tipo_doc->option("","Todos");
		$filter->tipo_doc->option("AB","COBRO A CLIENTES");
		$filter->tipo_doc->option("ND","NOTAS DE DEBITO");
		$filter->tipo_doc->option("NC","NOTAS DE CREDITO");
		$filter->tipo_doc->option("AN","ANTICIPOS");
		
		$filter->moneda = new dropdownField("Moneda", "moneda");
		$filter->moneda->style='width:200px;';
		$filter->moneda->option("","Todas las monedas" );
		$filter->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
												
		$filter->buttons("reset","search");
		$filter->build();
        
        
        function comp($tipo_doc,$transac,$serie,$numero,$cliente){
			
			switch ($tipo_doc){
			
				case 'RI':
					
					//$uri = anchor("ventas/smov/reintegro/show/$cliente/$tipo_doc/$numero/$serie","$serie-$numero");	
					$uri = "$serie-$numero";
					return($uri);
					break;
					
				case 'AB':
					
					$uri = anchor("ventas/smov/dataedit/show/$transac","R$serie-$numero");	
					return($uri);
					break;
				
				case 'AN':
				
					$uri = anchor("ventas/smov/dataedit/show/$transac","R$serie-$numero");
					return($uri);
					break;
					
				case 'FC':
				
					$uri = "F$serie-$numero";
					return($uri);
					break;
					
				case 'ND':
				
					$uri = "D$serie-$numero";
					return($uri);
					break;
					
				case 'NC':
				
					$uri = "C$serie-$numero";
					return($uri);
					break;
			
			}				        
   
			
		}
        
        $grid = new DataGrid2();
		$grid->order_by("fecha","DESC");
        $grid->use_function('comp');
		$grid->per_page=10;  
    
        $grid->column('Comprobante','<comp><#tipo_doc#>|<#transac#>|<#serie#>|<#numero#>|<#cod_cli#></comp>',"align='center'");
		$grid->column('N&uacute;mero'     ,'<#serie#>-<#numero#>',"align='center'");   
        $grid->column("Tipo"              ,"tipo_doc","tipo"  ,"align='center'");
        $grid->column_orderby('Fecha'         ,'<dbdate_to_human><#fecha#></dbdate_to_human>'  ,'fecha'  );
        $grid->column('Cliente','cod_cli');
		$grid->column('Nombre'  ,'nombre');
		$grid->column('Monto'   ,'<nformat><#monto#></nformat>','align=\'right\'');
		$grid->column("Moneda"              ,"moneda","moneda"  ,"align='center'");

       	//$grid->add("ventas/notas/dataedit/create",'Nota de Debito');		         
		
		$grid->totalizar('monto');
		$grid->build('datagridST');
		
		//echo $grid->db->last_query();
		
		$cana=$grid->recordCount;
		$grid=$grid->output;
		
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1100px; /* Required to set */
		    height: 250px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';

		$data['style']   = $style;
		$data['style']  .= style('superTables.css');
		
		IF($cana<=0){
			$data['content'] = '<div align="center">Ningun Resultado Obtenido</div>';	
		}ELSE{
			$data['content'] = $grid;		
		}


		$data['filtro']  = $filter->output;

		$data['title']   = heading("Movimientos de Clientes ");
		$data['script']  = script('jquery.js');
		$data["script"] .= script('superTables.js');
		$data['head']    = $this->rapyd->get_head();

		$this->load->view('view_ventanas', $data);
	}
	function _pre_delete2($do){
		
	    $id_rein=$do->get('id_rein');
		$numeroi=$do->get('numeroi');
		$monto  =$do->get('monto');
		 
		$this->db->query("UPDATE itabonos SET aplica=aplica-$monto WHERE id='$id_rein'");
		 
		logusu('sprm',"REINTEGRO  $numeroi al proveedor  ELIMINADO");
	
	}
	function reintegro(){
		
		$this->rapyd->load('dataedit');
        
		$script='
		<script type="text/javascript" >
			$(function(){
				$(".inputnum").numeric(".");
			});	
		</script>';
		

		$edit = new DataEdit(" ", "smov");
        $edit->back_url = site_url('finanzas/sprm/filteredgrid');
        
        $edit->pre_process('delete' ,'_pre_delete2');

		$edit->seriei = new inputField("Comprobante", "serie");
		$edit->seriei->rule= "required";
        $edit->seriei->style='width:200px;';
        $edit->seriei->mode="autohide";

		$edit->numeroi = new inputField("N&uacute;mero", "numero");
		$edit->numeroi->size = 12;
        $edit->numeroi->css_class ='inputnum';
		$edit->numeroi->maxlength=11;
		$edit->numeroi->in="seriei";
		$edit->numeroi->mode="autohide";
		
		$edit->cod_prv = new inputField("Cliente", "cod_cli");
		$edit->cod_prv->size = 7;
		$edit->cod_prv->maxlength=5;
        $edit->cod_prv->rule= "required";
        $edit->cod_prv->readonly  = true;
        $edit->cod_prv->mode="autohide";
		
		$edit->nombre = new inputField("Nombre", "nombre");
		$edit->nombre->size =  40;
		$edit->nombre->maxlength=80;
        $edit->nombre->readonly  = true;
        $edit->nombre->mode="autohide";
            				
		$edit->monto = new inputField('Monto', 'monto');
		$edit->monto->size = 10;
		$edit->monto->maxlength=15;
		$edit->monto->readonly  = true;
		$edit->monto->css_class ='inputnum';
		
		$edit->observa1 = new inputField("Observaci&oacute;n", "observa1");
		$edit->observa1->size = 7;
		
        $edit->buttons('save','delete','undo','back');	
        $edit->build();
        
        $data['content'] = $edit->output;
		$data['style']  = style('redmond/jquery-ui-1.8.1.custom.css');
		
		$data['script']  = script('jquery.js');
		$data['script'] .= script('jquery-ui.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.floatnumber.js');
		$data['script'] .= script('plugins/jquery.autocomplete.js');
		$data['script'] .= script('nformat.js');
		$data["script"] .= $script;
		$data['head']    = $this->rapyd->get_head();
			
		$data['title']   = heading("Creado por Reintegro de Proveedor");
		$data['content'] = $edit->output;
		$this->load->view('view_ventanas', $data);
		
		
	}
	function dataedit($estado,$itabono){
		
		$this->rapyd->load('dataedit');
        
       
		$edit = new DataEdit(" ", "itabonos");
        $edit->back_url = site_url('ventas/smov/filteredgrid');    
		
		
		$mSQL="SELECT a.*,b.control as letra FROM cobros as a 
		JOIN itpagos as b on a.idpago=b.id WHERE  itabono='$itabono' AND  a.tipo <> 'NC'";
		
        
        //Informacion de cod_cli

		$edit->pre_process('delete' ,'_pre_delete');
		
		$edit->id = new hiddenField(" ", 'id');
        
        $edit->tipoe = new hiddenField(" ", 'tipoe');
		$edit->tipoe->db_name  = 'tipo';
		
        $edit->fecha = new DateonlyField("Fecha", "fecha","d/m/Y");
		$edit->fecha->insertValue = date("Y-m-d");
		$edit->fecha->mode="autohide";
        $edit->fecha->rule= "required";
		$edit->fecha->size = 10;
		
		$edit->recepcion = new DateonlyField("Recepci&oacute;n", "recepcion","d/m/Y");
		$edit->recepcion->insertValue = date("Y-m-d");
        $edit->recepcion->rule= "required";
		$edit->recepcion->size = 10;
             
		$edit->serie = new dropdownField("Comprobante", "serie");
		$edit->serie->options("SELECT codigo, CONCAT_WS('-',codigo,descrip) AS descrip FROM serier ORDER BY codigo");
		$edit->serie->rule= "required";
        $edit->serie->style='width:250px;';

		$edit->numero = new inputField("N&uacute;mero", "numero");
		$edit->numero->size = 12;
		//$edit->numero->rule= "required";
        $edit->numero->css_class ='inputnum';
		$edit->numero->maxlength=11;
		$edit->numero->when=array('show');

		$edit->cod_cli = new inputField("C&oacute;digo", "cod_cli");
		$edit->cod_cli->size = 7;
		$edit->cod_cli->maxlength=5;
        $edit->cod_cli->rule= "required";
        $edit->cod_cli->readonly  = true;
        
        $edit->nombre = new inputField("Nombre", "nombre");
		$edit->nombre->size =  40;
		$edit->nombre->maxlength=80;
        $edit->nombre->readonly  = true;
    
		$edit->rif = new inputField("RUC", "rif");
		$edit->rif->size =  20;
		$edit->rif->maxlength=20; 
        $edit->rif->readonly  = true;
        
        $edit->condi1 = new inputField('Observaci&oacute;n', 'condi1');
		$edit->condi1->size =60;
		$edit->condi1->maxlength=50;
        
        $edit->ccosto = new  dropdownField ('Centro de Costo', 'ccosto');
        $edit->ccosto->option("001","Administraci&oacute;n");
		$edit->ccosto->option('002',"Operaci&oacute;n");
		$edit->ccosto->option('003','Importaci&oacute;n'); 
		$edit->ccosto->style='width:180px;';    
        
		$edit->moneda = new dropdownField("Moneda", "moneda");
		$edit->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY descrip");
		$edit->moneda->style='width:180px;';
		$edit->moneda->rule = 'required';
		$edit->moneda->group = "Precios";
		
		$edit->cambio = new inputField('Cambio', 'cambio');
		$edit->cambio->css_class ='inputnum';
		$edit->cambio->size      = 12; 
		
		$edit->referen = new inputField('N&uacute;mero de Operaci&oacute;n', 'referen');
		$edit->referen->css_class ='inputnum';
		$edit->referen->size      = 20; 
        
		$edit->monto = new inputField('', 'monto');
		$edit->monto->css_class ='inputnum';
		//$edit->monto->readonly  =true;
		$edit->monto->size      = 10;
        
        $edit->cuenta = new inputField('Cuenta', 'cuenta');
		$edit->cuenta->size     = 12;
		$edit->cuenta->rule     = 'required';
		
		$edit->formap = new dropdownField("Medio de Pago", "formap");
		$edit->formap->style='width:180px;';
		$edit->formap->options("SELECT formap,nombre FROM formap ORDER BY nombre");
        
        $edit->banco = new dropdownField("Banco", "banco");
		$edit->banco->style='width:180px;';
		//$edit->banco->options("SELECT banco, nombre FROM bancos ORDER BY nombre" );
		$edit->banco->options("SELECT codigo, CONCAT_WS('-',codigo,descrip) AS descri FROM serieg ORDER BY codigo");
		$edit->banco->group = "Informaci&oacute;n del Abono";
		
		$edit->comibanco = new inputField('- Comisi&oacute;n de Banco', 'comibanco');
		$edit->comibanco->css_class ='inputnum';
		$edit->comibanco->size      = 10;
		
		$edit->intbanco = new inputField('+ Intereses de Banco', 'intbanco');
		$edit->intbanco->css_class ='inputnum';
		$edit->intbanco->size      = 10;
        
        $edit->montob = new inputField('Ingreso al Banco', 'montob');
		$edit->montob->css_class ='inputnum';
		$edit->montob->readonly  =true;
		$edit->montob->size      = 10;
       
		$edit->usuario = new inputField('Usuario','usuario');
		    
        $edit->estampa = new DateonlyField("Registro", "estampa","Y-m-d");
		$edit->estampa->insertValue = date("Y-m-d");
        $edit->estampa->mode="autohide";
        $edit->estampa->when=array('show');
		
		$tipo  =$edit->_dataobject->get('tipo');
		$monto  =$edit->_dataobject->get('monto');
		$serie  =$edit->_dataobject->get('serie');
		$numero =$edit->_dataobject->get('numero');
        
        switch ($tipo){
			
		case 'AB':
			$data['title']   = heading('Cobro a Cliente '.$serie.'-'.$numero);
			break;
		
		case 'AN':
			$data['title']   = heading("Anticipo ".$serie.'-'.$numero." por $monto aplicado a las siguientes facturas");	
			break;
        
		}
        
        
        
        IF($this->super=='S'){
			$edit->buttons("save", "undo", "delete", "back");
		}ELSE{
			$edit->buttons("save", "undo", "back");
		}
			
        $edit->build();
		
		$mSQL_1=$this->db->query($mSQL);
		
		//echo $mSQL_1;
		$conten['result']=$mSQL_1->result();	
        
        $conten['form']  =&  $edit;
		$data['content'] = $this->load->view('view_smov', $conten,true);
		$data['style']  = style('redmond/jquery-ui-1.8.1.custom.css');
		
		$data['script']  = script('jquery.js');
		$data['script'] .= script('jquery-ui.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.floatnumber.js');
		$data['script'] .= script('nformat.js');

		$data['head']    = $this->rapyd->get_head();
		$this->load->view('view_ventanas', $data);
	}
	function _pre_delete($do){
		
		
        $id=$do->get('id');
        $tipo=$do->get('tipo');
        
        //echo $id;
        $cod_cli =$do->get('cod_cli');
        $numero  =$do->get('numero');
        
        $mSQL_1=$this->db->query("SELECT monto, idpago, itabono, id, cod_cli,  numero,serie FROM cobros WHERE itabono='$id'");
             
        foreach($mSQL_1->result() as $items ){
            
            $this->db->query("UPDATE smov SET abonos=abonos-'$items->monto' WHERE cod_cli='$items->cod_cli' AND numero='$items->numero'");
            
            $mSQL_2=$this->db->query("UPDATE itpagos SET abono=abono-'$items->monto' WHERE cod_cli='$items->cod_cli' AND id='$items->idpago'");      
			//$mSQL_3=$this->db->query("UPDATE letras  SET abono=abono-'$items->monto' WHERE cliente='$items->cod_cli' AND factura='$items->factura' AND serief='$items->serief' AND idpago='$items->idpago'");          
            
		}
        
        
        $mSQL_2=$this->db->query("DELETE FROM cobros WHERE itabono='$id'");
        $mSQL_3=$this->db->query("DELETE FROM bmov WHERE idabono='$id' AND clipro='C'");
        $mSQL_4=$this->db->query("DELETE FROM smov WHERE transac='$id' AND tipo_doc='$tipo'");
        
		logusu('ITABONOS',"COBRO al cliente $cod_cli numero $numero ELIMINADO");
	}
}
?>
